import datetime

import bot
import tvdb
from downloader import Downloader

def obtain_episodes_list(serie):
    s = serie.replace(' ', '+')
    search = 'http://www.google.com/search?hl=en&q='+s+'+episode+list+wikipedia'
    robot = bot.Bot(search, serie)
    return robot.obtain_info()

def obtain_downloads(user):
    date = datetime.date.today()
    dif = datetime.timedelta(days=1) #, hours=-2
    date = date - dif
    cals = tvdb.restore_calendar_by_date(user, date)
    pref = tvdb.load_preferences(user)
    download = Downloader()
    downloads = []
    if pref.count() > 0 and cals.count() > 0:
        for cal in cals:
            d = tvdb.obtain_downloads_model(cal.serie, pref[0].direct, pref[0].hosting, pref[0].formats)
            if d is None:
                d = download.obtain_links(cal, pref[0].direct, pref[0].hosting, pref[0].formats)
            if d is not None:
                downloads.append(d)
    elif cals.count() > 0:
        for cal in cals:
            d = tvdb.obtain_downloads_model(cal.serie)
            if d is None:
                d = download.obtain_links(cal)
            if d is not None:
                downloads.append(d)
    return downloads
